﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_FeeMonthTCDetail : Form
    {
        private DGBY.BLL.BYCompanyTab m_bllBYCompanyTab = new DGBY.BLL.BYCompanyTab();

        private DGBY.BLL.TCCompDataTab m_bllTCCompDataTab = new DGBY.BLL.TCCompDataTab();
        private DGBY.BLL.TCCompConPeoTelTab m_bllTCCompConPeoTelTab = new DGBY.BLL.TCCompConPeoTelTab();
        private DGBY.BLL.FacFeeTab m_bllFacFeeTab = new DGBY.BLL.FacFeeTab();
        private int m_nSelectFeeTTLoanTabID = 0;
        private DGBY.BLL.FeeInvoiceTab m_bllFeeInvoiceTab = new DGBY.BLL.FeeInvoiceTab();

        public Frm_FeeMonthTCDetail()
        {
            InitializeComponent();
        }
        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }

        private void InitCombox()
        {
            DataSet ds = m_bllTCCompDataTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxTCName.DataSource = ds.Tables[0];

                this.comboBoxTCName.ValueMember = "TCCompDataTabID";
                this.comboBoxTCName.DisplayMember = "拖车公司简称";
                this.comboBoxTCName.SelectedIndex = 0;
            }

            
        }
        private void Frm_FeeMonthTCDetail_Load(object sender, EventArgs e)
        {
            LocalPrintPreveiw();
            InitCombox();
        }

        private void comboBoxTCName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string str = this.comboBoxTCName.SelectedValue.ToString();
                
                int nID = Convert.ToInt32(str, 10);
                DataSet ds = m_bllTCCompDataTab.GetList("TCCompDataTabID = '" + nID + "'");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    this.textBoxQiChuRemainJinE.Text = ds.Tables[0].Rows[0]["期初余额"].ToString();
                }

                ds = m_bllTCCompConPeoTelTab.GetList("TCCompDataTabID = '" + nID + "'");
                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    this.textBoxTCPerson.Text = ds.Tables[0].Rows[0]["TCCompConPeoName"].ToString();
                }
                
            }
            catch { }
        }
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        private void MakeColumn(DataTable dt)
        {

            dt.Columns.Add("数量", System.Type.GetType("System.Int32"));
            dt.Columns["数量"].SetOrdinal(9);
            dt.Columns.Add("金额", System.Type.GetType("System.Decimal"));
            dt.Columns["金额"].SetOrdinal(11);
            dt.Columns.Add("其他项目", System.Type.GetType("System.String"));
            dt.Columns["其他项目"].SetOrdinal(12);
            dt.Columns.Add("其他项目金额", System.Type.GetType("System.Decimal"));
            dt.Columns["其他项目金额"].SetOrdinal(13);

        }
        private List<DateTime> FillDateTimeList(DataSet ds)
        {
            List<DateTime> lstDt = new List<DateTime>();
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DateTime dtFirst = (DateTime)ds.Tables[0].Rows[0]["申报日期"];
                DateTime dtLast = (DateTime)ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1]["申报日期"];

                for (int nYear = dtFirst.Year; nYear <= dtLast.Year; nYear++)
                {
                    int nFirstMonth = (nYear == dtFirst.Year) ? dtFirst.Month : 1;
                    int nEndMonth = (nYear == dtLast.Year) ? dtLast.Month : 12;
                    for (nFirstMonth = nFirstMonth; nFirstMonth <= nEndMonth; nFirstMonth++)
                    {
                        DateTime dtTemp = new DateTime(nYear, nFirstMonth, 1);
                        lstDt.Add(dtTemp);
                    }
                }

            }

            return lstDt;
        }

        private void ShowAllRecordInDataGridView()
        {
            DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
            DateTime dtEnd = LastDayOfMonth(this.dateTimePickerDate.Value);
            DataSet ds = m_bllFacFeeTab.ShowTCDetailRec("FeeInvoiceTab.TrueInvoiceJinE > 0"
                                + " and TCCompDataTab.TCCompDataTabID = '" + this.comboBoxTCName.SelectedValue.ToString() + "'"
                                + " and BGDComeBackTab.SBDate >= '" + dtFirst.Date + "'"
                                + " and BGDComeBackTab.SBDate <= '" + dtEnd.Date + "'"
                                + " and BYFeeKaiPiaoCateTab.BYFeeKaiPiaoCateName like " + "'%" + "运输" + "%'");
            
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                List<DateTime> lstDt = FillDateTimeList(ds);
                lstDt.Sort();


                DateTime dtFirstDayTemp = FirstDayOfMonth(this.dateTimePickerDate.Value);
                DateTime dtLastDayTemp = LastDayOfMonth(this.dateTimePickerDate.Value);

                Decimal dOrigQiChuRemainJinE = Convert.ToDecimal(this.textBoxQiChuRemainJinE.Text);
                Decimal dNextMonthRemainJinETemp = dOrigQiChuRemainJinE;//上个月期末余额

                Decimal dtThisMonthRemainJinETemp = 0;


                //计算出上个月期初余额
                foreach (DateTime dt in lstDt)
                {
                    Decimal dtDuoShaoTotal = 0;

                    DateTime dtFirstDay = FirstDayOfMonth(dt);
                    DateTime dtLastDay = LastDayOfMonth(dt);

                    DataSet ds2 = m_bllFacFeeTab.ShowTCDetailRec("FeeInvoiceTab.TrueInvoiceJinE > 0"
                                    + " and TCCompDataTab.TCCompDataTabID = '" + this.comboBoxTCName.SelectedValue.ToString() + "'"
                                    + " and BGDComeBackTab.SBDate >= '" + dtFirstDay.Date + "'"
                                    + " and BGDComeBackTab.SBDate <= '" + dtLastDay.Date + "'"
                                    + " and BYFeeKaiPiaoCateTab.BYFeeKaiPiaoCateName like " + "'%" + "运输" + "%'");

                    if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
                    {
                        Decimal dtTotal1 = 0;
                        Decimal dtShouldPayTrans1 = 0;
                        for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                        {
                            dtShouldPayTrans1 += Convert.ToDecimal(ds2.Tables[0].Rows[i]["应付运输费"].ToString());
                            Decimal dtTemp = Convert.ToDecimal(ds2.Tables[0].Rows[i]["总金额"].ToString());
                            dtTotal1 += dtTemp;
                        }


                        dtDuoShaoTotal = dtTotal1 - dtShouldPayTrans1;
                    }


                    if (dtFirstDay.Date.CompareTo(dtFirstDayTemp.Date) == 0)
                    {
                        this.textBoxQiChuRemainJinE.Text = dNextMonthRemainJinETemp.ToString();
                        break;
                    }

                    dtThisMonthRemainJinETemp = dNextMonthRemainJinETemp;
                    dNextMonthRemainJinETemp = dtThisMonthRemainJinETemp + dtDuoShaoTotal;
                }

                MakeColumn(ds.Tables[0]);
                DataTable dtNew = null;
                dtNew = ds.Tables[0].Clone();
                Decimal dtTotal = 0;
                Decimal dtShouldPayTrans = 0;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dtShouldPayTrans += Convert.ToDecimal(ds.Tables[0].Rows[i]["应付运输费"].ToString());
                    Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[i]["总金额"].ToString());
                    dtTotal += dtTemp;
                    Decimal dtTransPrice = Convert.ToDecimal(ds.Tables[0].Rows[i]["运价"].ToString());
                    int nCount = (int)(dtTemp / dtTransPrice);
                    Decimal dtJinE = nCount * dtTransPrice;
                    Decimal dtOtherJinE = dtTemp - dtJinE;
                    ds.Tables[0].Rows[i]["数量"] = nCount;
                    ds.Tables[0].Rows[i]["金额"] = dtJinE;
                    ds.Tables[0].Rows[i]["其他项目"] = "运杂费";
                    ds.Tables[0].Rows[i]["其他项目金额"] = dtOtherJinE;
                    dtNew.Rows.Add(ds.Tables[0].Rows[i].ItemArray);
                }


                DataRow dr = dtNew.NewRow();
                dr["发货人"] = "合计";
                dr["总金额"] = dtTotal;

                dtNew.Rows.Add(dr);

                this.textBoxShouldPay.Text = dtShouldPayTrans.ToString();
                Decimal dtDuoShao = dtTotal - dtShouldPayTrans;
                this.textBoxInvoiceJinE.Text = dtDuoShao.ToString();
                Decimal dtAccuTemp = Convert.ToDecimal(this.textBoxQiChuRemainJinE.Text);
                Decimal dtAccuTrue = dtAccuTemp + dtDuoShao;
                this.textBoxAccuInvoiceJinE.Text = dtAccuTrue.ToString();
                Decimal dtTax = dtAccuTrue * (Decimal)0.038;
                this.textBoxTax.Text = dtTax.ToString();

                ultraGrid1.DataSource = dtNew;
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
                ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
                ultraGrid1.DisplayLayout.Bands[0].Columns[2].Hidden = true;
                ultraGrid1.DisplayLayout.Bands[0].Columns[3].Hidden = true;
                ultraGrid1.DisplayLayout.Bands[0].Columns[4].Hidden = true;
                ProcessMultiHeader();
            }
           
        }
        private void ProcessMultiHeader()
        {
            int nSpanX = 0;
            int nOriginX = 0;
            int nOriginXTemp = 0;
            bool bSpan = false;
            UltraGridColumn ultraGridColumn1 = null;
            UltraGridColumn ultraGridColumn2 = null;
            foreach (UltraGridColumn column2 in this.ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                string str = column2.Header.Caption;
                if (str == "总金额")
                    bSpan = false;

                if (!bSpan)
                {
                    if (str == "运输项目及金额" || str == "其他项目及金额")
                        continue;
                    column2.RowLayoutColumnInfo.SpanY = 4;
                    if (column2.Hidden == false)
                        nOriginXTemp += 2;
                }
                else
                {
                    nSpanX += 2;
                    column2.RowLayoutColumnInfo.OriginY = 2;
                }
                if (str == "发票号码")
                {
                    bSpan = true;
                    nOriginX = nOriginXTemp;
                }
            }

            ultraGridColumn1 = ultraGrid1.DisplayLayout.Bands[0].Columns.Add("运输项目及金额", "运输项目及金额");
            ultraGridColumn1.CellActivation = Activation.Disabled;
            ultraGridColumn1.SortIndicator = SortIndicator.Disabled;
            ultraGridColumn1.RowLayoutColumnInfo.PreferredCellSize = new Size(1, 1);
            ultraGridColumn1.RowLayoutColumnInfo.AllowLabelSizing = RowLayoutSizing.None;
            ultraGridColumn1.RowLayoutColumnInfo.LabelPosition = LabelPosition.LabelOnly;
            ultraGridColumn1.RowLayoutColumnInfo.OriginX = nOriginX;//有2个列隐藏了
            ultraGridColumn1.RowLayoutColumnInfo.OriginY = 0;
            ultraGridColumn1.RowLayoutColumnInfo.SpanX = nSpanX - 4;
            ultraGridColumn1.RowLayoutColumnInfo.SpanY = 2;

            ultraGridColumn1 = ultraGrid1.DisplayLayout.Bands[0].Columns.Add("其他项目及金额", "其他项目及金额");
            ultraGridColumn1.CellActivation = Activation.Disabled;
            ultraGridColumn1.SortIndicator = SortIndicator.Disabled;
            ultraGridColumn1.RowLayoutColumnInfo.PreferredCellSize = new Size(1, 1);
            ultraGridColumn1.RowLayoutColumnInfo.AllowLabelSizing = RowLayoutSizing.None;
            ultraGridColumn1.RowLayoutColumnInfo.LabelPosition = LabelPosition.LabelOnly;
            ultraGridColumn1.RowLayoutColumnInfo.OriginX = nOriginX + 8;//有2个列隐藏了
            ultraGridColumn1.RowLayoutColumnInfo.OriginY = 0;
            ultraGridColumn1.RowLayoutColumnInfo.SpanX = nSpanX-8;
            ultraGridColumn1.RowLayoutColumnInfo.SpanY = 2;
        }
        
        private void buttonImport_Click(object sender, EventArgs e)
        {
            ShowAllRecordInDataGridView();
        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            string strTemp = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[5].Text;
            if (strTemp == "合计")
                return;
            string strFeeTTLoanTabID = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[1].Text;
            m_nSelectFeeTTLoanTabID = Convert.ToInt32(strFeeTTLoanTabID, 10);
            cellFeeTTLoanTabClick();
        }
        private void cellFeeTTLoanTabClick()
        {
            DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(m_nSelectFeeTTLoanTabID);
            if (modelFeeInvoiceTab != null)
            {
                this.textBoxFInvoiceNo.Text = modelFeeInvoiceTab.InvoiceNo;
                

            }
        }

        private void buttonModify_Click(object sender, EventArgs e)
        {
            try
            {
                DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(m_nSelectFeeTTLoanTabID);
                if (modelFeeInvoiceTab == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                modelFeeInvoiceTab.InvoiceNo = this.textBoxFInvoiceNo.Text;

                m_bllFeeInvoiceTab.Update(modelFeeInvoiceTab);
                ShowAllRecordInDataGridView();
                MessageBox.Show("数据修改成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        
        }

        private void ultraGrid1_InitializeRow(object sender, Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e)
        {

        }

        private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            ultraGrid1.DisplayLayout.Bands[0].UseRowLayout = true;
            ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void ultraGridExcelExporter1_CellExported(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.CellExportedEventArgs e)
        {
            Worksheet ws = e.CurrentWorksheet;
            if (e.CurrentColumnIndex == 0)
            {
                Infragistics.Excel.IWorksheetCellFormat cfCellFmt;
                Infragistics.Excel.IWorksheetCellFormat cfCellFmt2;
                string stringt = "";
                if (e.Value != null)
                {
                    stringt = e.Value.ToString();
                    //e.Value = null;
                }
                if (stringt == "合计")
                {
                    int iRdex = e.CurrentRowIndex;
                    int iCdex = e.CurrentColumnIndex;
                    //ws.Rows[iRdex].Cells[iCdex - 1].Value = "";

                    cfCellFmt = e.CurrentWorksheet.Rows[iRdex].Cells[iCdex].CellFormat;
                    cfCellFmt.LeftBorderStyle =
          Infragistics.Excel.CellBorderLineStyle.None;
                    cfCellFmt2 = e.CurrentWorksheet.Rows[iRdex].Cells[iCdex + 8].CellFormat;
                    cfCellFmt2.RightBorderStyle =
          Infragistics.Excel.CellBorderLineStyle.None;

                    // Create a merged region that will be a header to the column headers
                    Infragistics.Excel.WorksheetMergedCellsRegion mergedRegion1 =
                      ws.MergedCellsRegions.Add(iRdex, iCdex, iRdex, iCdex + 8);

                    // Set the value of the merged region
                    mergedRegion1.Value = stringt;

                    // Give the merged region a solid background color
                    mergedRegion1.CellFormat.FillPattern =
                      Infragistics.Excel.FillPatternStyle.Solid;
                    mergedRegion1.CellFormat.FillPatternForegroundColor = Color.White;

                    // Set the cell alignment of the middle cell in the merged region.
                    // Since a cell and its merged region shared a cell format, this will 
                    // ultimately set the format of the merged region
                    ws.Rows[iRdex].Cells[iCdex].CellFormat.Alignment =
                      Infragistics.Excel.HorizontalCellAlignment.Center;
                }

            }
        }

        private void ultraGridExcelExporter1_BeginExport(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.BeginExportEventArgs e)
        {
            DataSet ds = m_bllBYCompanyTab.GetList("CompanyName like '%进出口%'");
            string strTemp = "";
            string strTelTemp = "";
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                strTemp = ds.Tables[0].Rows[0]["纳税人识别码"].ToString();
                strTelTemp = ds.Tables[0].Rows[0]["电话"].ToString();
            }

            DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
            //DateTime dtEnd = LastDayOfMonth(this.dateTimePickerDate.Value);
            dtFirst.Month.ToString();
            Worksheet ws = e.CurrentWorksheet;

            //ws.Columns[4].Width = 20 * 256;
            //ws.Columns[5].Width = 20 * 256;
            ws.Rows[1].Cells[4].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
            ws.Rows[2].Cells[4].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;

            ws.Rows[1].Cells[0].Value = @"TO:" + this.comboBoxTCName.Text + this.textBoxTCPerson.Text;
            ws.Rows[1].Cells[3].Value = @"FROM: 百业/吴小姐 " + strTelTemp;

            ws.Rows[2].Cells[0].Value = this.comboBoxTCName.Text + @"开票明细（" + dtFirst.Month.ToString() + "月）";

            ws.Rows[3].Cells[0].Value = @"收货人：东莞市百业进出口公司";
            ws.Rows[4].Cells[0].Value = @"纳税编码：" + strTemp;

            e.CurrentRowIndex = 5;
        }

        private void ultraGridExcelExporter1_EndExport(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.EndExportEventArgs e)
        {
            Worksheet ws = e.CurrentWorksheet;
            int a = e.CurrentRowIndex;
            ws.Rows[a++].Cells[0].Value = "注：";
            ws.Rows[a++].Cells[0].Value = "1.在运输项目及金额栏中：必须填上重量（数量），单位运价，";
            ws.Rows[a++].Cells[0].Value = "2.在备注栏中：必须填表上起运地：东莞， 到达地：深圳";
            ws.Rows[a].Cells[0].Value = "应付金额：RMB " + this.textBoxShouldPay.Text;
            ws.Rows[a].Cells[3].Value = @"多/少开发票金额: " + this.textBoxInvoiceJinE.Text;
            ws.Rows[a++].Cells[6].Value = @"累计多/少开发票金额: " + this.textBoxAccuInvoiceJinE.Text;
            Decimal dtTemp = Convert.ToDecimal(this.textBoxAccuInvoiceJinE.Text);
            if(dtTemp < 0)
                ws.Rows[a].Cells[0].Value = "应付税金：0";
            else
                ws.Rows[a].Cells[0].Value = "应付税金：" + this.textBoxTax.Text; 
        }
    }
}
